import os
import time
import webbrowser
from zipfile import ZipFile, ZIP_DEFLATED
from tkinter import TOP, LEFT, IntVar
from tkinter.messagebox import showinfo
from tkinter.ttk import Button, Frame, LabelFrame, Label, Checkbutton
from taobao_check.tools import PATH, run_async, open_file_by_notepad, delete_file


class ConfigTab(Frame):
    def __init__(self, version, config, root):
        Frame.__init__(self)
        self.timeout = 30
        self.version = version
        self.config = config
        self.root = root
        self.platform = {}
        self.debug = {}
        self.init_data()
        self.init_platform()
        self.init_debug()
        self.init_update()
        self.pack()

    def init_platform(self):
        platform_frame = LabelFrame(self, height=300, text="验号方式")
        btn_frame = Frame(platform_frame)
        for name, info in self.config.platform_zh.items():
            check = IntVar()
            check.set(int(info))
            self.platform[name] = check
            Checkbutton(btn_frame, text=name, variable=check).pack(side=LEFT, padx=30, pady=10)

        btn_frame.pack(side=TOP)
        save_btn = Button(platform_frame, text="保存", cursor='hand2', width=10, command=self.save_platform)
        save_btn.pack(side=TOP, anchor='center', padx=50, pady=10)
        platform_frame.pack(side=TOP, fill='x', pady=5)

    def save_platform(self):
        for name, info in self.platform.items():
            self.config.platform_zh[name] = bool(info.get())
        self.config.save_platform()
        showinfo(title="成功", message="验号方式保存成功！")

    def init_debug(self):
        platform_frame = LabelFrame(self, height=300, text="debug(开发人员使用)")
        debug_list = [(i, self.config.debug_zh[i]) for i in self.config.user.debug]
        debug_list = [debug_list[i:i+6] for i in range(0, len(debug_list), 6)]
        for debugs in debug_list:
            btn_frame = Frame(platform_frame)
            for name, info in debugs:
                check = IntVar()
                check.set(int(info))
                self.debug[name] = check
                Checkbutton(btn_frame, text=name, variable=check).pack(side=LEFT, padx=20, pady=10)
            btn_frame.pack(side=TOP)

        save_btn = Button(platform_frame, text="保存", cursor='hand2', width=10, command=self.save_debug)
        save_btn.pack(side=TOP, anchor='center', padx=50, pady=10)
        platform_frame.pack(side=TOP, fill='x', pady=5)

    def save_debug(self):
        for name, info in self.debug.items():
            self.config.debug_zh[name] = bool(info.get())
        self.config.save_debug()
        showinfo(title="成功", message="debug方式保存成功！")

    def init_data(self):
        # 用户数据模块
        data_frame = LabelFrame(self, height=400, text="用户数据")

        # tip_label = Label(data_frame, text="请先停止验号再清空数据！清空数据后需要重启软件才能生效！", font=("微软雅黑", 10), foreground="red")
        # tip_label.pack(side=TOP, anchor='center', padx=20, pady=10)

        btn_frame = Frame(data_frame)
        Button(btn_frame, text="查看黑名单", cursor='hand2', width=12, command=self.open_blacklist)\
            .pack(side=LEFT, anchor='center', padx=35, pady=20)

        Button(btn_frame, text="查看已刷名单", cursor='hand2', width=12, command=self.open_used).\
            pack(side=LEFT, anchor='center', padx=35, pady=20)

        Button(btn_frame, text="打包日志", cursor='hand2', width=12, command=self.zip_log).\
            pack(side=LEFT, anchor='center', padx=35, pady=20)

        btn_frame.pack(side=TOP)
        data_frame.pack(side=TOP, fill='x', pady=5)

    def init_update(self):
        # 更新模块
        update_frame = LabelFrame(self, height=400, text="检查更新")
        pwd_label = Label(update_frame, text="提取密码为: 2021", font=("微软雅黑", 10), foreground="red")
        pwd_label.pack(side=TOP, anchor='center', padx=20, pady=10)

        self.update_label = Label(update_frame, text="正在检查是否有更新版本，请稍候...", font=("微软雅黑", 10), foreground="green")
        self.update_label.pack(side=TOP, anchor='center', padx=20, pady=10)
        # 检查更新的按钮
        update_btn = Button(update_frame, text="下载更新", cursor='hand2', width=10, command=self.open_update)
        update_btn.pack(side=TOP, anchor='center', padx=50, pady=20)

        update_frame.pack(side=TOP, fill='both', pady=5)

    def set_update(self, config):
        latest_version = config["latest_version"]
        print(f"最新版本: V{latest_version}")
        if latest_version <= self.version:
            self.update_label.config(text="当前版本为最新版.")
            return
        if config["auto"]:
            self.update_label.config(text=f"最新版本: V{latest_version}. 重启后自动更新.")
        else:
            self.update_label.config(text=f"最新版本: V{latest_version}. 请手动下载更新.")

    @run_async
    def open_blacklist(self):
        open_file_by_notepad(PATH.blacklist)

    @run_async
    def open_used(self):
        open_file_by_notepad(PATH.used)

    @run_async
    def clear_blacklist(self):
        delete_file(PATH.blacklist, "黑名单")

    @run_async
    def clear_used(self):
        delete_file(PATH.used, "已刷名单")

    @run_async
    def open_update(self):
        webbrowser.open("https://memory233.lanzoui.com/b00ucfw5a")

    @run_async
    def zip_log(self):
        timestamp = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
        zip_name = PATH.log / f"{self.config.user.name}_log_{timestamp}.zip"
        with ZipFile(zip_name, 'w', compression=ZIP_DEFLATED, compresslevel=6) as myzip:
            for file in PATH.log.rglob("*.txt"):
                myzip.write(file)
        os.system(f"start explorer {PATH.log}")
    # @run_async
    # def check_update(self):
    #     """
    #     Returns:
    #
    #     """
    #     while True:
    #         config = get_web_file("https://gitee.com/MemoryD/TaobaoCheck/raw/master/config/update.json")
    #         if not config:
    #             self.update_label.config(text="检查更新失败，请手动查看是否有更新版本.")
    #             return
    #         config = json.loads(config)
    #         latest_version = config["latest_version"]
    #         print(f"最新版本: V{latest_version}")
    #         if latest_version <= self.version:
    #             self.update_label.config(text="当前版本为最新版.")
    #             return
    #         if config["auto"]:
    #             self.update_label.config(text=f"最新版本: V{latest_version}. 重启后自动更新.")
    #         else:
    #             self.update_label.config(text=f"最新版本: V{latest_version}. 请手动下载更新.")
    #
    #         # self.root.set_title(latest_version)
    #
    #         time.sleep(7200)
